use clap::{Parser, Subcommand};
use std::path::PathBuf;

#[derive(Parser)]
#[command(name = "ftp-config")]
#[command(about = "FTP Server and Client Configuration Manager")]
pub struct ConfigCli {
    #[command(subcommand)]
    pub command: ConfigCommand,
}

#[derive(Subcommand)]
pub enum ConfigCommand {
    /// 生成默认配置文件
    Generate {
        /// 配置文件类型 (server|client)
        #[arg(short, long)]
        config_type: String,
        
        /// 输出文件路径
        #[arg(short, long)]
        output: Option<PathBuf>,
    },
    
    /// 验证配置文件
    Validate {
        /// 配置文件路径
        #[arg(short, long)]
        config: PathBuf,
        
        /// 配置文件类型 (server|client)
        #[arg(short, long)]
        config_type: String,
    },
    
    /// 显示配置摘要
    Summary {
        /// 配置文件路径
        #[arg(short, long)]
        config: PathBuf,
        
        /// 配置文件类型 (server|client)
        #[arg(short, long)]
        config_type: String,
    },
    
    /// 应用环境变量覆盖
    ApplyEnv {
        /// 配置文件路径
        #[arg(short, long)]
        config: PathBuf,
        
        /// 配置文件类型 (server|client)
        #[arg(short, long)]
        config_type: String,
        
        /// 输出文件路径
        #[arg(short, long)]
        output: Option<PathBuf>,
    },
}

pub fn run_config_manager() -> anyhow::Result<()> {
    let cli = ConfigCli::parse();
    
    match cli.command {
        ConfigCommand::Generate { config_type, output } => {
            generate_config(&config_type, output)?;
        }
        ConfigCommand::Validate { config, config_type } => {
            validate_config(&config, &config_type)?;
        }
        ConfigCommand::Summary { config, config_type } => {
            show_config_summary(&config, &config_type)?;
        }
        ConfigCommand::ApplyEnv { config, config_type, output } => {
            apply_env_overrides(&config, &config_type, output)?;
        }
    }
    
    Ok(())
}

fn generate_config(config_type: &str, output: Option<PathBuf>) -> anyhow::Result<()> {
    let output_path = output.unwrap_or_else(|| {
        match config_type {
            "server" => PathBuf::from("config/server.toml"),
            "client" => PathBuf::from("config/client.toml"),
            _ => PathBuf::from("config.toml"),
        }
    });
    
    match config_type {
        "server" => {
            let config_content = include_str!("../../config/server.toml");
            std::fs::write(&output_path, config_content)?;
            println!("Generated server config: {}", output_path.display());
        }
        "client" => {
            let config_content = include_str!("../../config/client.toml");
            std::fs::write(&output_path, config_content)?;
            println!("Generated client config: {}", output_path.display());
        }
        _ => {
            return Err(anyhow::anyhow!("Invalid config type: {}", config_type));
        }
    }
    
    Ok(())
}

fn validate_config(config_path: &PathBuf, config_type: &str) -> anyhow::Result<()> {
    match config_type {
        "server" | "client" => {
            let content = std::fs::read_to_string(config_path)?;
            toml::from_str::<toml::Value>(&content)?;
            println!("✓ {} config is valid", config_type);
        }
        _ => {
            return Err(anyhow::anyhow!("Invalid config type: {}", config_type));
        }
    }
    
    Ok(())
}

fn show_config_summary(config_path: &PathBuf, config_type: &str) -> anyhow::Result<()> {
    match config_type {
        "server" | "client" => {
            let content = std::fs::read_to_string(config_path)?;
            let config: toml::Value = toml::from_str(&content)?;
            println!("{} Configuration Summary:", config_type);
            println!("{:#}", config);
        }
        _ => {
            return Err(anyhow::anyhow!("Invalid config type: {}", config_type));
        }
    }
    
    Ok(())
}

fn apply_env_overrides(config_path: &PathBuf, config_type: &str, output: Option<PathBuf>) -> anyhow::Result<()> {
    let output_path = output.unwrap_or_else(|| config_path.clone());
    
    match config_type {
        "server" | "client" => {
            let content = std::fs::read_to_string(config_path)?;
            let mut config: toml::Value = toml::from_str(&content)?;
            
            // 简单的环境变量覆盖逻辑
            if let Ok(host) = std::env::var("FTP_HOST") {
                if let Some(server) = config.get_mut("server") {
                    if let Some(host_field) = server.get_mut("host") {
                        *host_field = toml::Value::String(host);
                    }
                }
            }
            
            let updated_content = toml::to_string_pretty(&config)?;
            std::fs::write(&output_path, updated_content)?;
            println!("Applied environment overrides to {} config: {}", config_type, output_path.display());
        }
        _ => {
            return Err(anyhow::anyhow!("Invalid config type: {}", config_type));
        }
    }
    
    Ok(())
}
